package com.example.netcenter;


import android.support.annotation.NonNull;

import com.example.netcenter.Event.ProgressListener;
import com.example.netcenter.Log.MyHttpLoggingInterceptor;
import com.example.netcenter.MyConverFactory.CustomGsonConverterFactory;
import com.example.netcenter.Url.ApiService;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.Url.ServerAddress;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;


//wkh
public class RetrofitBuilder {


    private static Retrofit.Builder retrofitUtil;

    //单例锁模式
    public static Retrofit.Builder getRetrofitUtil() {
        if (retrofitUtil == null) {
            synchronized (RetrofitBuilder.class) {
                if (retrofitUtil == null) {
                    getCommonRetrofitBuilder();
                }
            }
        }
        return retrofitUtil;
    }


    static Retrofit.Builder getCommonRetrofitBuilder() {

        retrofitUtil = new Retrofit.Builder().baseUrl(ServerAddress.ServerAddress).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create());

        if (BuildConfig.DEBUG) {
            OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
            MyHttpLoggingInterceptor logging = new MyHttpLoggingInterceptor();
            builder.addInterceptor(logging);
            OkHttpClient client = builder.build();
            retrofitUtil.client(client);
        }
        return retrofitUtil;

    }


    public static void DownloadFileProgress(final ProgressListener listener, Callback<ResponseBody> callback) {


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS).build();


        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .baseUrl(ServerAddress.DownLoadAddress)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create());
        OkHttpClient client = okHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                okhttp3.Response response = chain.proceed(chain.request());
                return response.newBuilder().body(new ProgressResponseBody(response.body(), listener)).build();
            }
        }).build();

        ApiService downloadRetrofit = retrofitBuilder.client(client).build().create(ApiService.class);

        //   downloadRetrofit.downloadFile().enqueue(callback);


    }

    public static void UpLoadImage(List<String> imagePaths, String supplierId, String goodsName, String sourceCity,
                                   String packing, String sizeDesc, String priceUnit, String price, String note,
                                   final com.example.netcenter.Event.UpLoadResponse MyResponse) {
        //多张图片
        List<File> files = new ArrayList<>();
        for (String path : imagePaths) {
            files.add(new File(path));  //图片压缩
        }
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (files != null && files.size() > 0) {
            for (File file : files) {
                RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
                requestBody.addFormDataPart("imgs", file.getName(), body);
            }

            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart("method", ConstantsCode.new_goods_add)
                    .addFormDataPart("supplierId", supplierId)
                    .addFormDataPart("goodsName", goodsName)
                    .addFormDataPart("sourceCity", sourceCity)
                    .addFormDataPart("packing", packing)
                    .addFormDataPart("sizeDesc", sizeDesc)
                    .addFormDataPart("priceUnit", priceUnit)
                    .addFormDataPart("price", price)
                    .addFormDataPart("note", note);
        }

        Request request = new Request.Builder().url(ServerAddress.UpLoadAddress).post(requestBody.build()).build();
        // readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS)
                .build()
                .newCall(request)
                .enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        MyResponse.UpLoadFail(call, e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String string = response.body().string();
                        MyResponse.UpLoad(string);

                    }
                });
    }




    /**
     * 根据传入的baseUrl，和api创建retrofit
     */
    public static ApiService CreateApi() {
        Retrofit retrofit = getRetrofitUtil().build();
        return retrofit.create(ApiService.class);
    }


}
